package cn.tedu.contorller;

import cn.tedu.dao.UserDao;
import cn.tedu.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "LoginServlet",urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("name");
        String password = request.getParameter("pwd");


        UserDao dao = new UserDao();
        User user = dao.login(username,password);

        if (user==null){
            response.sendRedirect(request.getContextPath()+"/ShowLoginServlet");
        }else{
            //创建Session保存登录状态
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            String rem = request.getParameter("rem");
            if (rem!=null){
                //将中文的username使用url编码保存到Cookie中
                username = URLEncoder.encode(username,"utf-8");
                Cookie c1 = new Cookie("username",username);
                Cookie c2 = new Cookie("password",password);
                //将Cookie下发到浏览器
                response.addCookie(c1);
                response.addCookie(c2);
            }
            response.sendRedirect(request.getContextPath()+"/HomeServlet");
        }

    }


}
